import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
import router from '@/router'
import qs from 'qs'

const request = axios.create({
// baseURL:'',
// timeout:()=>{}
})
function refrushToken () {
  return axios.create()({
    method: 'post',
    url: '/front/user/refresh_token',
    data: qs.stringify({
      refreshtoken: store.state.user.refresh_token
    })
  })
}
function redirectLogin () {
  router.push({
    name: 'login',
    query: {
      rediract: router.currentRoute.fullPath
    }
  })
}

let isRefrush = true
let requests: (() => void)[] = []

// 请求拦截器
request.interceptors.request.use(function (config) {
  const { user } = store.state
  if (user && user.access_token) {
    // eslint-disable-next-line
    config.headers.Authorization = store.state.user.access_token
  }
  return config
}, function (error) {
  return Promise.reject(error)
})
// 响应拦截器
request.interceptors.response.use(function (response) {
  // 自定义错误状态码 错误处理
  const { user } = store.state
  if (user && user.access_token) {
    response.headers.Authorization = store.state.user.access_token
  }
  return response
}, async function (error) {
  // 默认http状态码，错误处理
  if (error.response) {
    // response code range of 2xx
    const { status } = error.response
    if (status === 400) {
      Message.error('请求参数错误')
    } else if (status === 401) {
      if (!store.state.user) {
        redirectLogin()
        return Promise.reject(error)
      }
      if (isRefrush) {
        isRefrush = false
        return refrushToken().then(res => {
          if (!res.data.success) {
            throw new Error('刷新 token 失败')
          }
          store.commit('setUser', res.data.content)
          requests.forEach(cb => cb())
          requests = []
          return request(error.config)
        }).catch(error => {
          store.commit('setUser', null)
          redirectLogin()
          return Promise.reject(error)
        }).finally(() => {
          isRefrush = true
        })
      }
      return new Promise(resolve => {
        requests.push(() => {
          resolve(request(error.config))
        })
      })
      // try {
      //   const { data } = await axios.create()({
      //     method: 'post',
      //     url: '/front/user/refresh_token',
      //     data: qs.stringify({
      //       refreshtoken: store.state.user.refresh_token
      //     })
      //   })
      //   store.commit('setUser', data.content)
      //   return request(error.config)
      // } catch (error) {
      //   store.commit('setUser', null)
      //   router.push({
      //     name: 'login',
      //     query: {
      //       rediract: router.currentRoute.fullPath
      //     }
      //   })
      //   return Promise.reject(error)
      // }
    } else if (status === 403) {
      Message.error('请求未授权，请联系管理员')
    } else if (status === 404) {
      Message.error('请求资源不存在')
    } else if (status >= 500) {
      Message.error('服务端内部错误，请联系管理员')
    }
  } else if (error.request) {
    // no response request
    Message.error('请求超时，请重试')
  } else {
    // set error
    Message.error('请求失败:' + error.message)
  }
  return Promise.reject(error)
})
export default request
